
import { InsertResult, Repository, UpdateResult } from "typeorm";
import { DaoBase } from "../../src/engine/dao/DaoBase";
import DateUtil from "../../src/engine/utils/DateUtil";
import { DBSourceManager } from "../../src/engine/utils/DBSourceManager";
import { ClubUserEntity } from "../entity/ClubUserEntity";
import { ClubConfig } from "../config/ClubConfig"
import { Logger } from "../../src/engine/utils/Logger";
import { JhaoProto } from "../../src/lib/net/protobuf/jhaoproto";
import { ResultSetHeader } from "mysql2";

export class ClubUserDao extends DaoBase {

    public static Tb_Name: string = "t_clubusers";

    public static async getRepository() {
        let repository: Repository<ClubUserEntity> = await this.getRepositoryBase(ClubUserEntity, this.getGameDbName())
        return repository;
    }

    public static async get_club_user_by_id(id:number): Promise<ClubUserEntity>{
        let repository: Repository<ClubUserEntity> = await this.getRepository()
        let result: ClubUserEntity = await repository.findOneBy({
            id: id,
        })
        return result
    }

    public static async get_club_user(clubid: number, userid:number): Promise<ClubUserEntity> {
        let repository: Repository<ClubUserEntity> = await this.getRepository()
        let result: ClubUserEntity = await repository.findOneBy({
            clubid: clubid,
            userid:userid
        })
        return result
    }


    public static async add_club_user(clubid: number, userid: number, actor: number, user_state: number): Promise<boolean> {
        let entity: ClubUserEntity = new ClubUserEntity()
        entity.clubid = clubid
        entity.userid = userid
        entity.user_state = user_state
        entity.actor = actor
        entity.join_time = DateUtil.formatDateStr(DateUtil.now())
        let repository: Repository<ClubUserEntity> = await this.getRepository()
        let result: InsertResult = await DBSourceManager.instance.insert(repository, entity)
        if (result && result.raw["affectedRows"] > 0) {
            return true
        }
        return false
    }

    
    public static async update_user(entity: ClubUserEntity) {
        let repository: Repository<ClubUserEntity> = await this.getRepository()
        let result: ClubUserEntity
        if (!repository.hasId(entity)) {
            result = await repository.save(entity)
        } else {
            let updateResult:UpdateResult = await repository.update({ id:entity.id }, entity)
            if (updateResult && updateResult.affected > 0) {
                result = entity
            }
        }
        return result
    }


    public static async getUserCountByClub(clubid: number) {
        let repository: Repository<ClubUserEntity> = await this.getRepository()
        let count: number = await repository.countBy({
            clubid: clubid,
            user_state: ClubConfig.Club_merber_state_type.nomal
        })
        return count
    }

    public static async req_club_apply_list(clubid: number) {
        let sql: string = "select * from " + this.Tb_Name + ",t_users where `t_clubusers`.`clubid` = ? and `t_clubusers`.`user_state`=0 and `t_clubusers`.`userid`=`t_users`.`userid`"
        let sqlParams: Array<any> = [clubid];
        let repository: Repository<ClubUserEntity> = await this.getRepository()
        let results = await repository.query(sql, sqlParams)
        let users: Array<JhaoProto.IClub_User> = this.obj2IClubUserList(results)
        return users
    }

    public static async club_apply_handle(id: number, isAgree: boolean, apply_userid: number) {
        let sql: string = "update t_clubusers set `user_state`=?, `approver`=?  where `id`=?";
        let user_state: number = ClubConfig.Club_merber_state_type.nomal
        if (!isAgree) {
            user_state = ClubConfig.Club_merber_state_type.refuse
        }
        let sqlParams: Array<any> = [user_state, apply_userid, id];
        let repository: Repository<ClubUserEntity> = await this.getRepository()
        let results:ResultSetHeader = await repository.query(sql, sqlParams)
        // Logger.log("club_apply_handle==", results)
        if(results.affectedRows > 0){
            return true
        }else{
            return false
        }
    }

    private static obj2IClubUserList(results:Array<object>){
        let users: Array<JhaoProto.IClub_User> = []
        for (let i = 0; i < results.length; i++) {
            let user: JhaoProto.IClub_User = {
                id: results[i]["id"],
                clubid: results[i]["clubid"],
                userid: results[i]["userid"],
                userState: results[i]["user_state"],
                actor: results[i]["actor"],
                joinTime: new Date(results[i]["join_time"]).getTime(),
                approver: results[i]["approver"],
                score: results[i]["score"],
                headimgurl: results[i]["headimgurl"],
                nickName: results[i]["nick_name"],
            }
            users[i] = user
        }
        return users
    }

    public static async req_club_member_list(clubid:number){
        let sql: string = "select * from " + this.Tb_Name + ",t_users where `t_clubusers`.`clubid` = ? and `t_clubusers`.`user_state`=? and `t_clubusers`.`userid`=`t_users`.`userid`"
        let sqlParams: Array<any> = [clubid, ClubConfig.Club_merber_state_type.nomal];
        let repository: Repository<ClubUserEntity> = await this.getRepository()
        let results = await repository.query(sql, sqlParams)
        let users: Array<JhaoProto.IClub_User> = this.obj2IClubUserList(results)
        return users
    }




}